const ejs = require('ejs');
const fs = require('fs');
const path = require('path');

const ejsCompile = (templatePath, data = {}, options = {}) => {
  // console.log('传入模板的数据：', templatePath, data, options)
  return new Promise((resolve, reject) => {
    ejs.renderFile(templatePath, {data}, options, (err, str) => {
      if(err) {
        reject(err)
        return;
      }
      resolve(str);
    })
  })
}

const mkdirSync = (dirname) => {
  if(fs.existsSync(dirname)) {
    return true;
  } else {
    // 不存在？ 查看父文件路径是否存在
    if(mkdirSync(path.dirname(dirname))) {
      // 存在父文件，直接创建新文件
      fs.mkdirSync(dirname);
      return true;
    }
  }
}

const writeFile = (path, content) => {
  if(fs.existsSync(path)) {
    console.log('The file already exists ~');
    return;
  }
  return fs.promises.writeFile(path, content)
}

module.exports = {
  ejsCompile,
  mkdirSync,
  writeFile
}